package com.baohua.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baohua.exception.BaohuaSystemException;
import com.baohua.model.Role;
import com.baohua.model.Staff;
import com.baohua.service.RoleService;
import com.baohua.service.StaffService;
import com.baohua.util.ExcelUtil;

@Controller
@RequestMapping("/staff")
public class StaffController {
 
	/**
	 * 跳转到员工主页面
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "staffList";
	}
	
	/**
	 * 根据条件查询员工列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/list")
	public @ResponseBody Map queryList(Staff staff, HttpServletRequest request){
		
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String pre_employDate = request.getParameter("pre_employDate");
		String af_employDate = request.getParameter("af_employDate");
		String pre_leaveDate = request.getParameter("pre_leaveDate");
		String af_leaveDate = request.getParameter("af_leaveDate");
		
		String active = request.getParameter("i_active");
		String sex = request.getParameter("i_sex");
		
		Map map = staffService.queryStaff(staff, pre_employDate, af_employDate, pre_leaveDate, af_leaveDate, active, sex, page, pageSize);
	    return map;
	}
	
	/**
	 * 增加员工信息
	 * @param staff
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public String addStaff(Staff staff, HttpServletRequest request) {
		String[] roleIds = request.getParameterValues("add_roles");
		String date = request.getParameter("add_employDate");
		try{
			staffService.addStaff(staff, date, roleIds);
	    } catch (BaohuaSystemException e) {
	    		logger.info(e.getMessage());
	    		request.setAttribute("errorMessage", e.getMessage());
	    		return "forward:/system/error";
		} catch (ParseException e) {
			    logger.info(e.getMessage());
				request.setAttribute("errorMessage", "增加员工失败, 日期转换错误");
				return "forward:/system/error";
		}
	    	
		return "redirect:/staff/index";
	}
	
	/**
	 * 异步删除员工信息
	 * @param rowsNum
	 * @return
	 */
	@RequestMapping(value="/del/{rowsNum}", method=RequestMethod.GET)
	public @ResponseBody String delStaff(@PathVariable String rowsNum) {
// 		String s = request.getParameter("rowsNum");
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			String[] staffIds = objectMapper.readValue(rowsNum, String[].class);
			for(String staffId : staffIds) {
				staffService.delStaff(Integer.parseInt(staffId));
			}
		} catch (JsonParseException e) {
			logger.info(e.getMessage());
			return "{message:systemerror}";
		} catch (JsonMappingException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (IOException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (NumberFormatException e) {
			logger.info(e.getMessage());
			return "{message:'systemerror'}";
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			return "{message:'error'}";
		}
		return "{message : 'success'}";
	}
	
	/**
	 * 根据员工ID查询员工角色
	 * @param staffId
	 * @return
	 */
	@RequestMapping(value="/getRoles/{staffId}", method=RequestMethod.GET)
	public @ResponseBody Map getRoles(@PathVariable String staffId) {
		Map map = new HashMap();
		try {
			List<Integer> list = staffService.queryRolesById(Integer.parseInt(staffId));
			List<Role> roles = roleService.queryRole();
			map.put("roles", roles);
			map.put("roleIds", list);
		} catch (NumberFormatException e) {
			logger.info(e.getMessage());
		} catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
		}
		return map;
	}
	
	/**
	 * 修改员工信息
	 * @param staff
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String updateStaff(Staff staff, HttpServletRequest request){
		String ispassword = request.getParameter("ispassword");
		String employDate1 = request.getParameter("update_employDate");
		String  leaveDate1 = request.getParameter("update_leaveDate");
		String[] roleIds = request.getParameterValues("update_roles");
		
		//2、取得修改员工信息的角色, 并赋值
		try {
			 if(roleIds!=null && roleIds.length>0) {
				Set<Role> roles = new HashSet<Role>();
				for(String roleId : roleIds) {
			    	int id = Integer.parseInt(roleId);
						Role role = roleService.queryRoleById(id);
						System.out.println(role.getRoleName());
						roles.add(role);
				}
				staff.setRoles(roles);
			}
			
		// 3、转换入职日期	
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			    
		    	if(employDate1!=null && (!"".equals(employDate1.trim()))){
		    		staff.setEmployDate(sdf.parse(employDate1));
		    	}
	    // 4、转换离职日期	    	
		    	if(leaveDate1!=null && (!"".equals(leaveDate1.trim()))){
		    		staff.setLeaveDate(sdf.parse(leaveDate1));
		    	}
			
			if(StringUtils.equals("1", ispassword)) {
				//如果为true, 初始化密码为123,并加密
				staff.setPassword(DigestUtils.md5Hex("123"));
			}
			
			staffService.updateStaff(staff);
		}
		catch (BaohuaSystemException e) {
			logger.info(e.getMessage());
			request.setAttribute("errorMessage", e.getMessage());
			return "forward:/system/error";
		} catch (ParseException e) {
			logger.info(e.getMessage());
			request.setAttribute("errorMessage", e.getMessage());
			return "forward:/system/error";
		}
		return "redirect:/staff/index";
	}
	
	@RequestMapping("export")
	public String export(HttpServletRequest request, HttpServletResponse response) {
		List<Staff> list = new ArrayList<Staff>(); 
		String param = request.getParameter("param");
		try {
			if(!StringUtils.isBlank(param)) {
			  String[] staffNOs = param.split(",");
			 list = staffService.queryByStaffNOs(staffNOs);
			}
			
			Date date = new Date();
			staffService.exportData("员工列表" + date.getTime() + ".xls", 
					list, "员工列表", request, response);
		} catch (IllegalArgumentException e) {
			logger.info(e.getMessage());
		} catch (IOException e) {
			logger.info(e.getMessage());
		} catch (IllegalAccessException e) {
			logger.info(e.getMessage());
		}
		return null;
	}
	
	
		
	private static final Logger logger = Logger.getLogger(StaffController.class.getName());
    private StaffService staffService;
	private RoleService roleService;

	public RoleService getRoleService() {
		return roleService;
	}

	@Resource(name="roleService")
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public StaffService getStaffService() {
		return staffService;
	}

	@Resource(name="staffService")
	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}
	
}
